package parser;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import data.FastWordOccurrenceMap;
import data.Mail;

public class MailCacheWriter
{
	private DataOutputStream dataOutputStream;
	private HashMap<String, Integer> vocabularyIndexes;
	
	
	public MailCacheWriter(OutputStream outputStream, List<String> vocabulary)
	{
		dataOutputStream = new DataOutputStream(outputStream);
		this.vocabularyIndexes = new HashMap<>(vocabulary.size());
		for (int i = 0; i < vocabulary.size(); i++)
		{
			vocabularyIndexes.put(vocabulary.get(i), i);
		}
	}
	
	public void write(Mail mail) throws IOException
	{
		dataOutputStream.writeInt(-1);
		
		dataOutputStream.writeUTF(mail.getFileName());
		dataOutputStream.writeBoolean(mail.isSpam());
		
		FastWordOccurrenceMap wordOccurrenceMap = mail.getWordOccurrenceMap();
		for (Map.Entry<Integer, Integer> entry : wordOccurrenceMap.entrySet())
		{
			int wordIndex = entry.getKey();
			int occurrence = entry.getValue();
			
			//System.out.println(wordIndex + " : " + occurrence);
			dataOutputStream.writeInt(wordIndex);
			dataOutputStream.writeInt(occurrence);
		}
	}
}
